package album

import (
	"blog/app/common"
	"blog/app/model/album"
	"blog/app/services/system"
	"blog/core"
	"errors"
)

type Images struct {
}

// GetLists , 获得相册下的图片
func (i Images) GetLists(id int) ([]album.ImagesAlbum, int64) {
	var lists []album.ImagesAlbum
	var count int64
	core.DbConnect.Model(system.Model.AlbumImagesModel).Where("aid = ?", id).Count(&count).Find(&lists)
	var hash []string
	for _, v := range lists {
		hash = append(hash, v.Url)
	}

	hashLists := common.Cache.Files(hash)

	for i := 0; i < len(lists); i++ {
		if _, ok := hashLists[lists[i].Url]; ok {
			lists[i].Url = hashLists[lists[i].Url]
		}
	}

	return lists, count
}

// Del , 删除相册图片
func (i Images) Del(aid, id int) error {
	var count int64
	if core.DbConnect.Model(&system.Model.AlbumModel).Where("id = ?", aid).Count(&count); count == 0 {
		return errors.New("相册不存在")
	}

	count = 0

	if core.DbConnect.Model(system.Model.AlbumImagesModel).Where("aid = ? AND id = ?", aid, id).Count(&count); count == 0 {
		return errors.New("图片不存在")
	}

	return core.DbConnect.Where("id = ? AND aid = ?", id, aid).Delete(&album.ImagesAlbum{}).Error
}
